package com.pixiv.controller;

import cn.hutool.json.JSONObject;
import com.pixiv.Entity.*;
import com.pixiv.service.LabelService;
import com.pixiv.service.NoticeService;
import com.pixiv.service.TitleService;
import com.pixiv.service.UserService;
import com.pixiv.tools.SendPack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/position")
public class PositionController {

    @Autowired
    private LabelService labelService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private TitleService titleService;
    @Autowired
    private UserService userService;
    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 前往主站的行为
     * @return
     */
    @RequestMapping("gotoPosition")
    public ModelAndView gotoLogin(){
        return new ModelAndView("/pixiv/index");
    }

    /**
     *前往用户设置行为
     * @return
     */
    @RequestMapping("gotoSetUser")
    public ModelAndView gotoSetUser(){
        return new ModelAndView("/pixiv/set/setuser");
    }

    /**
     * 前往我的展示行为
     * @return
     */
    @RequestMapping("gotoSetInfo")
    public ModelAndView gotoSetInfo(){

        return new ModelAndView("/pixiv/set/setinfo");
    }


    @RequestMapping("gotoSetID")
    public ModelAndView gotoSetID(){
        return new ModelAndView("/pixiv/set/setid");
    }

    @RequestMapping("gotoSetIcon")
    public ModelAndView gotoSetIcon(){
        return new ModelAndView("/pixiv/set/seticon");
    }

    @RequestMapping("gotoCoverChange")
    public ModelAndView gotoCoverChange(){
        return new ModelAndView("/pixiv/set/setcover");
    }

    /**
     * 进入我的图库里触发的函数和页面切换
     * @param hs
     * @return
     */
    @RequestMapping("gotoMyTitle")
    public ModelAndView gotoMyTitle(HttpSession hs){
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        u.getVar().push_vector("GLOBAL_Select_User_ID",u.getUserID() );
        ModelAndView modelAndView = new ModelAndView("/pixiv/titleshow/showmytitlepicture");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("loadUserInformation")
    public String initUserInformation(HttpServletRequest req, HttpServletResponse resp)
    {
        HttpSession hs = req.getSession();
        User user = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        User selectUser = userService.getUser((Integer) user.getVar().get_vector("GLOBAL_Select_User_ID"));
        //User.getUser((Integer) user.getVar().get_vector("GLOBAL_Select_User_ID"));
        if (selectUser != null)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("flag",1);
            jsonObject.accumulate("selectUserID",selectUser.getUserID() );
            jsonObject.accumulate("name",selectUser.getName() );
            jsonObject.accumulate("email",selectUser.getEMail() );

            jsonObject.accumulate("total",userService.getTitleTotal(selectUser.getUserID()) );

            List<TitlePicture> hm = userService.getUserTitles(selectUser.getUserID());
            jsonObject.accumulate("titles",hm );

            System.out.println(jsonObject.toString() );
            return jsonObject.toString();
        }
        return SendPack.getFlag(0);
    }

    /**
     * 获得当前所有的标签
     */
    @ResponseBody
    @RequestMapping("getLabels")
    public String getLabels_Test(){

        ArrayList<PictureLabel> list = labelService.getPictureLabel();
        JSONObject json=new JSONObject();
        json.accumulate("size",list.size());
        json.accumulate("count",10);
        json.accumulate("code",0);
        json.accumulate("msg","null");
        json.accumulate("data",list);
        return json.toString();
    }

    /**
     * 获得当前发布的所有公告帖子
     * @return
     */
    @ResponseBody
    @RequestMapping("getNotices")
    public String getNotices(){

        List<Notice> lst = noticeService.getNotices(null,null);

        JSONObject json=new JSONObject();
        json.accumulate("count",10);
        json.accumulate("code",0);
        json.accumulate("msg","null");
        json.accumulate("data",lst);

        return json.toString();
    }

    /**
     * 获取了所有的信息帖子，其中count代表次数
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("getNewTitle")
    public String getNewTitle(){

        //ApplicationContext ac = new ClassPathXmlApplicationContext("Spring.xml");
        ArrayList<TitlePicture> al = new ArrayList();
        List<Map<String, Object>> map =  jdbcTemplate.queryForList("select * from titleLst limit " + 5);
        Iterator i = map.iterator();

        JSONObject json=new JSONObject();

        while (i.hasNext())
        {
            Map<String,Object> obj = (Map<String, Object>) i.next();

            int userID = (int) obj.get("userid");
            TitlePicture atp = new TitlePicture();//ac.getBean(TitlePicture.class);
            atp.setTitleUUID(String.valueOf(obj.get("titleid")));
            atp.setTitleCaption(String.valueOf(obj.get("titleCaption")));
            atp.setTitleContext(String.valueOf(obj.get("titleExplosion")));
            atp.setTitleLabel(String.valueOf(obj.get("label")));
            atp.setAgeLimit((int) obj.get("ageLimit"));
            atp.setOrginal((int) obj.get("orginalPicture"));
            atp.setUploadTime(String.valueOf(obj.get("uploadTime")));
            atp.setUserid(userID);
            al.add(atp);
        }
        json.accumulate("titles",al);

        if (map.size() > 0)
            json.accumulate("flag",1);
        else
            json.accumulate("flag",0);
        return json.toString();
    }



    /**
     * 获得用户自己的图片
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody
    @RequestMapping("getUserTitle")
    public String getUserTitle(HttpServletRequest req, HttpServletResponse resp) {

        //ApplicationContext ac = new ClassPathXmlApplicationContext("Spring.xml");
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        ArrayList<TitlePicture> al = new ArrayList();
        List<Map<String, Object>> map = jdbcTemplate.queryForList("select * from titleLst where userid = " + u.getUserID());
        Iterator i = map.iterator();

        JSONObject json=new JSONObject();

        while (i.hasNext()) {
            Map<String, Object> obj = (Map<String, Object>) i.next();

            int userID = (int) obj.get("userid");
            TitlePicture atp = new TitlePicture();
            atp.setTitleUUID(String.valueOf(obj.get("titleid")));
            atp.setTitleCaption(String.valueOf(obj.get("titleCaption")));
            atp.setTitleContext(String.valueOf(obj.get("titleExplosion")));
            atp.setTitleLabel(String.valueOf(obj.get("label")));
            atp.setAgeLimit((int) obj.get("ageLimit"));
            atp.setOrginal((int) obj.get("orginalPicture"));
            atp.setUploadTime(String.valueOf(obj.get("uploadTime")));
            atp.setUserid(userID);
            al.add(atp);
        }
        json.accumulate("titles", al);
        if (map.size() > 0)
            json.accumulate("flag",1);
        else
            json.accumulate("flag",0);

        return json.toString();
    }


    @ResponseBody
    @RequestMapping("getEtcTitle")
    public String getEtcTitle(HttpServletRequest req, HttpServletResponse resp) {

        //ApplicationContext ac = new ClassPathXmlApplicationContext("Spring.xml");
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        ArrayList<TitlePicture> al = new ArrayList();

        List<Map<String, Object>> map = jdbcTemplate.queryForList("select * from titleLst where userid != " + u.getUserID());
        Iterator i = map.iterator();

        JSONObject json=new JSONObject();

        while (i.hasNext()) {
            Map<String, Object> obj = (Map<String, Object>) i.next();

            int userID = (int) obj.get("userid");
            TitlePicture atp = new TitlePicture();
            atp.setTitleUUID(String.valueOf(obj.get("titleid")));
            atp.setTitleCaption(String.valueOf(obj.get("titleCaption")));
            atp.setTitleContext(String.valueOf(obj.get("titleExplosion")));
            atp.setTitleLabel(String.valueOf(obj.get("label")));
            atp.setAgeLimit((int) obj.get("ageLimit"));
            atp.setOrginal((int) obj.get("orginalPicture"));
            atp.setUploadTime(String.valueOf(obj.get("uploadTime")));
            atp.setUserid(userID);
            al.add(atp);
        }
        json.accumulate("titles", al);
        if (map.size() > 0)
            json.accumulate("flag",1);
        else
            json.accumulate("flag",0);

        return json.toString();
    }

    @ResponseBody
    @RequestMapping("initOpenTitle")
    public String initOpenTitle(HttpServletRequest req){

        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        String uuid = req.getParameter("UUID");
        //System.out.println("initOpenTitleuuid:" + uuid);
        u.getVar().push_vector("GLOBAL_Title_UUID",uuid);
        return SendPack.getFlag(1);
    }

    /**
     * 切换到帖子显示
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping("switchTitle")
    public ModelAndView switchTitle(HttpServletRequest req, HttpServletResponse resp){
        return new ModelAndView("/pixiv/titleshow/showtitle");
    }

    @RequestMapping("gotoTitle")
    public ModelAndView gotoTitle(HttpServletRequest req, HttpServletResponse resp){
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        String uuid = req.getParameter("uuid");
        //System.out.println("initOpenTitleuuid:" + uuid);
        u.getVar().push_vector("GLOBAL_Title_UUID",uuid);
        return new ModelAndView("/pixiv/titleshow/showtitle");
    }

    /**
     * 初始化发送了一次帖子信息的初始化包
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody
    @RequestMapping("SendShowTitlePacket")
    public String SendShowTitlePacket(HttpServletRequest req, HttpServletResponse resp){
        HttpSession hs = req.getSession();
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        String uuid = (String) u.getVar().get_vector("GLOBAL_Title_UUID");
        TitlePicture titlePicture = titleService.getTitle(uuid);
        int userid = titlePicture.getUserid();
        User writeUser = userService.getUser(userid);
        //User writeUser = User.getUser(userid);

        titlePicture.setTitleUUID(uuid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("flag",1);
        jsonObject.accumulate("caption",titlePicture.getCaption());
        jsonObject.accumulate("context",titlePicture.getContext());
        jsonObject.accumulate("label",titlePicture.getLabel());
        jsonObject.accumulate("ageLimit", titlePicture.getAgeLimit() );
        jsonObject.accumulate("orgin",titlePicture.getOrginal());
        jsonObject.accumulate("uplaodTime", titlePicture.getUploadTime());
        jsonObject.accumulate("userid", titlePicture.getUserid() );


        jsonObject.accumulate("name",writeUser.getUserName() );
        jsonObject.accumulate("uuid", uuid );
        jsonObject.accumulate("pictureTotal",titleService.getTitleSubPictureTotal(uuid));
        System.out.println(jsonObject.toString());
        return jsonObject.toString();

    }


    /**
     *
     */
    @RequestMapping("gotoShowUserInfor")
    public ModelAndView gotoShowUserInfor(HttpSession hs){
        User u = (User) hs.getAttribute("GLOBAL_USER_OBJECT");
        String uuid = (String) u.getVar().get_vector("GLOBAL_Title_UUID");

        TitlePicture titlePicture = titleService.getTitle(uuid);
        int id = titlePicture.getUserid();
        User writeUser = userService.getUser(id);
        u.getVar().push_vector("GLOBAL_Select_User_ID",writeUser.getUserID() );
        ModelAndView modelAndView = new ModelAndView("/pixiv/titleshow/showuserinfor");
        return modelAndView;
    }


}
